package algotithm.leetcode.dp.hot.test5;

/**
 * @author 25068
 * @Date 2021/6/27 18:29
 * @Title 5. 最长回文子串
 */
public class Main {

    public static void main(String[] args) {
        Main m = new Main();
        String s = "babad";
        String res = m.longestPalindrome(s);
        System.out.println(res);
    }

    public String longestPalindrome(String s) {
        int maxLen = 1;
        int n = s.length();
        if (n < 2) {
            return s;
        }
        boolean[][] dp = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
        }
        int begin = 0;
        char[] c = s.toCharArray();
        for (int L = 2; L <= n; L++) {
            for (int i = 0; i < n; i++) {
                int j = i + L - 1;
                if (j >= n) {
                    break;
                }
                if (c[i] != c[j]) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][ j - 1];
                    }

                }

                if (dp[i][j] && j - i + 1 > maxLen) {
                    maxLen = j - i + 1;
                    begin = i;
                }
            }
        }
        return s.substring(begin,begin + maxLen);
    }

}
